<template>
  <lay-container fluid="true" class="organization-box">
    <div style="display: flex">
      <div :style="{ width: isFold ? `0px` : `300px` }" class="left-tree">
        <!-- tree -->
        <div v-show="!isFold">
          <lay-button type="normal" size="sm" @click="toAdd">
            <lay-icon type="layui-icon-addition"></lay-icon>
            新建
          </lay-button>
          <lay-button type="warm" size="sm" @click="toEdit">
            <lay-icon type="layui-icon-edit"></lay-icon>
            修改
          </lay-button>
          <lay-button type="danger" size="sm" @click="toDelete">
            <lay-icon type="layui-icon-delete"></lay-icon>
            删除
          </lay-button>
        </div>

        <lay-tree
            v-show="!isFold"
            style="margin-top: 10px"
            :data="data"
            v-model:selectedKey="selectedKey"

            @node-click="handleClick"
        >
          <template #title="{ data }">
            <span :class="selectedKey == data.id ? 'isChecked' : ''">
              {{ data.title }} {{ data.id }}
            </span>
          </template>
        </lay-tree>

        <div class="isFold" @click="isFold = !isFold">
          &nbsp;<lay-icon v-if="!isFold" class="layui-icon-left"></lay-icon>
          <lay-icon v-else class="layui-icon-right"></lay-icon>
        </div>
      </div>

      <div style="flex: 1; padding: 10px; over-flow: auto">
        <!-- table -->
        <lay-card>
          <lay-form>
            <lay-row>
              <lay-col :md="5">
                <lay-form-item label="用户名" label-width="80">
                  <lay-input
                      v-model="searchQuery.name"
                      placeholder="请输入"
                      size="sm"
                      :allow-clear="true"
                      style="width: 98%"
                  ></lay-input>
                </lay-form-item>
              </lay-col>
              <lay-col :md="5">
                <lay-form-item label="状态" label-width="80">
                  <lay-select
                      class="search-input"
                      size="sm"
                      v-model="searchQuery.status"
                      :allow-clear="true"
                      placeholder="请选择"
                  >
                    <lay-select-option
                        value="true"
                        label="启用"
                    ></lay-select-option>
                    <lay-select-option
                        value="false"
                        label="禁用"
                    ></lay-select-option>
                  </lay-select>

                </lay-form-item>
              </lay-col>
              <lay-col :md="5">
                <lay-form-item label="手机号" label-width="80">
                  <lay-input
                      v-model="searchQuery.phone"
                      placeholder="请输入"
                      size="sm"
                      :allow-clear="true"
                      style="width: 98%"
                  ></lay-input>
                </lay-form-item>
              </lay-col>
              <lay-col :md="5">
                <lay-form-item label="性别" label-width="80">
                  <lay-select
                      class="search-input"
                      size="sm"
                      v-model="searchQuery.sex"
                      :allow-clear="true"
                      placeholder="请选择"
                  >
                    <lay-select-option
                        value="男"
                        label="男"
                    ></lay-select-option>
                    <lay-select-option
                        value="女"
                        label="女"
                    ></lay-select-option>
                  </lay-select>
                </lay-form-item>
              </lay-col>
              <lay-col :md="5">
                <lay-form-item label-width="20">
                  <lay-button
                      style="margin-left: 20px"
                      type="normal"
                      size="sm"
                      @click="toSearch"
                  >
                    查询
                  </lay-button>
                  <lay-button size="sm" @click="toReset"> 重置</lay-button>
                </lay-form-item>
              </lay-col>
            </lay-row>
          </lay-form>
        </lay-card>

        <lay-table
            :resize="true"
            :page="page"
            :height="'50%'"
            :columns="columns"
            :loading="loading"
            :default-toolbar="true"
            :data-source="dataSource"
            v-model:selected-keys="selectedKeys"
            @change="change"
            @sortChange="sortChange"
        >
          <template #status="{ row }">

            <lay-switch
                :model-value="row.status"
                onswitch-text="启用"
                unswitch-text="禁用"
                @change="changeStatus($event, row)">
            </lay-switch>

          </template>
          <template #roleName="{ row }">
            <lay-tag color="#165DFF" variant="light">{{ row.roleName }}</lay-tag>
          </template>

          <template v-slot:toolbar>
            <lay-button
                size="sm"
                type="primary"
                @click="changeVisible11('新增', null)"
            >新增
            </lay-button
            >
            <lay-button size="sm" @click="toRemove">删除</lay-button>
          </template>
          <template v-slot:operator="{ row }">
            <lay-button
                size="xs"
                border="green"
                border-style="dashed"
                @click="changeVisible11('编辑', row)"
            >编辑
            </lay-button
            >
            <lay-popconfirm
                content="确定要删除此用户吗?"
                @confirm="confirm"
                @cancel="cancel"
            >
              <lay-button size="xs" border="red" border-style="dashed"
              >删除
              </lay-button
              >
            </lay-popconfirm>
          </template>
        </lay-table>
      </div>
    </div>

    <lay-layer v-model="visible11" :title="title" :area="['500px', '450px']">
      <div style="padding: 20px">
        <lay-form :model="model11" ref="layFormRef11" required>
          <lay-form-item label="用户账号" prop="account">
            <lay-input v-model="model11.account"></lay-input>
          </lay-form-item>
          <lay-form-item label="用户名" prop="name">
            <lay-input v-model="model11.name"></lay-input>
          </lay-form-item>
          <lay-form-item label="性别" prop="sex">
            <lay-select v-model="model11.sex" style="width: 100%">
              <lay-select-option value="男" label="男"></lay-select-option>
              <lay-select-option value="女" label="女"></lay-select-option>
            </lay-select>
          </lay-form-item>
          <lay-form-item label="角色" prop="role">
            <lay-input v-model="model11.role"></lay-input>
          </lay-form-item>
          <lay-form-item label="状态" prop="status">
            <lay-switch :model-value="model11.status"></lay-switch>
          </lay-form-item>
        </lay-form>
        <div style="width: 100%; text-align: center">
          <lay-button size="sm" type="primary" @click="toSubmit"
          >保存
          </lay-button
          >
          <lay-button size="sm" @click="toCancel">取消</lay-button>
        </div>
      </div>
    </lay-layer>

    <!--    左侧树添加-->
    <lay-layer v-model="visible22" :title="title22" :area="['700px', '400px']">
      <div style="padding: 20px">
        <lay-form :model="model22" ref="layFormRef11" required>
          <lay-row>
            <lay-col md="12">
              <lay-form-item label="所属学院" prop="parentId">
                <lay-select v-model="model22.parentId" style="width: 100%" :show-search="true" :multiple="false"
                            :allow-clear="true">
                  <lay-select-option v-for="item in collegeList" :value="item.id" :label="item.title">
                  </lay-select-option>
                </lay-select>
              </lay-form-item>

              <lay-form-item label="名称" prop="name">
                <lay-input v-model="model22.name"></lay-input>
              </lay-form-item>
            </lay-col>

            <lay-col md="12">
              <lay-form-item label="类型" prop="category">
                <lay-select v-model="model22.category" style="width: 100%">
                  <lay-select-option value="class" label="班级"></lay-select-option>
                  <lay-select-option value="college" label="学院"></lay-select-option>
                </lay-select>
              </lay-form-item>

              <lay-form-item label="排序号" prop="sort">
                <lay-input-number
                    style="width: 100%"
                    v-model="model22.sort"
                    position="right"
                ></lay-input-number>
              </lay-form-item>
              <lay-form-item label="备注" prop="remark">
                <lay-textarea
                    placeholder="请输入备注"
                    v-model="model22.remark"
                    :rows="4"
                ></lay-textarea>
              </lay-form-item>

            </lay-col>

          </lay-row>
        </lay-form>
        <div style="width: 100%; text-align: center">
          <lay-button size="sm" type="primary" @click="toSubmitTree"
          >保存
          </lay-button
          >
          <lay-button size="sm" @click="toCancel">取消</lay-button>
        </div>
      </div>
    </lay-layer>
  </lay-container>
</template>
<script setup lang="ts">
import {ref, reactive, onMounted} from 'vue'
import {layer} from '@layui/layui-vue'
import {getCollegeList, getTreeList, treeInsert, getPage} from "@/api/system/organization";
import {userUpdate} from "@/api/system/user";


onMounted(() => {
  //左侧树
  fetchDataTree();
  getTablePage();
})

//查询左侧列表
const fetchDataTree = () => {
  getTreeList().then(res => {
    //console.log('res的值是：',res)
    if (res.code == 0 && res.data.length > 0) {
      let resultData = res.data;
      data.value = resultData;
    }
  })
}

const collegeList = ref();
//获取所有学院
const fucCollegeList = () => {
  getCollegeList().then(res => {
    if (res.code == 0 && res.data.length > 0) {
      collegeList.value = res.data;
    }

  })
}

const getTablePage = () => {
  //没关系
  searchQuery.value.index = page.index;
  searchQuery.value.size = page.size;

  getPage(searchQuery.value).then(res => {
    //console.log("右侧的值是：", res)
    if (res.code == 0 && res.data.records.length > 0) {
      dataSource.value = res.data.records;
      page.total = res.data.total;
    }else{
      dataSource.value ='';
    }
  })

}

//左侧树对象
const data = ref()
const showLine = ref(false)
const selectedKey = ref('')
const selectedNode = ref({
  id: 0,
  title: ''
})
const isFold = ref(false)
const searchQuery = ref({
  id:'',
  name: '',
  status: '',
  phone: '',
  sex: '',
  collegeName:'',
  className:'',
  index: 0,
  size: 0
})

function toReset() {
  searchQuery.value = {
    name: '',
    status: '',
    phone: '',
    sex: '',
    collegeName:'',
    className:'',
    index: 0,
    size: 0,
    id:''
  }
}

function handleClick(node: any) {

  console.log('点击了节点', node)
  model22.value = {
    id: node.id,
    name: node.title,
    category: node.category,
    parentId: node.parentId
  }

  selectedNode.value = JSON.parse(JSON.stringify(node))
  //page.current = selectedNode.value.id
  let cate = node.category;
  if (cate == 'class'){
    searchQuery.value.className = node.title
    searchQuery.value.collegeName = '';
  }else if(cate == 'college'){
    searchQuery.value.collegeName = node.title;
    searchQuery.value.className = '';
  }

  change(page)
}

//左侧树添加
function toAdd() {
  //设置上级的下拉值
  model22.value = {
    id:'',
    name: '',
    category: '',
    parentId: ''
  }
  fucCollegeList();

  visible22.value = true


}

function toEdit() {
  fucCollegeList();
  visible22.value = true
}

function toDelete() {
  if (selectedKey.value == '') {
    layer.msg('您未选择组织机构，请先选择要删除的组织机构', {
      icon: 3,
      time: 2000
    })
    return
  }
  layer.confirm(
      '您将删除所选中的组织机构 [ ' + selectedNode.value.title + ' ] ？',
      {
        title: '提示',
        btn: [
          {
            text: '确定',
            callback: (id: any) => {
              layer.msg('您已成功删除')
              layer.close(id)
            }
          },
          {
            text: '取消',
            callback: (id: any) => {
              layer.msg('您已取消操作')
              layer.close(id)
            }
          }
        ]
      }
  )
}

function toSearch() {
  page.index = 1
  change(page)
}

const loading = ref(false)
const selectedKeys = ref()
const page = reactive({index: 1, size: 10, total: 0})
const columns = ref([
  {title: '选项', width: '55px', type: 'checkbox', fixed: 'left'},
  {title: '编号', width: '50px', key: 'id', fixed: 'left', sort: 'id'},
  {title: '用户名', width: '80px', key: 'name', sort: 'name', ellipsisTooltip: "true"},
  {title: '性别', width: '50px', key: 'sex', sort: 'sex'},
  {title: '角色', width: '80px', key: 'roleName', customSlot: "roleName"},

  {title: '城市', width: '120px', key: 'city',},
  {title: '年龄', width: '50px', key: 'age', sort: 'age', ellipsisTooltip: "true"},
  {title: '手机号', width: '120px', key: 'phone', ellipsisTooltip: "true"},
  {title: '班级', width: '100px', key: 'className',},
  {title: '学院', width: '120px', key: 'collegeName', ellipsisTooltip: "true"},
  {
    title: '状态',
    width: '70px',
    key: 'status',
    customSlot: "status"
  },
  {
    title: '创建时间',
    width: '120px',
    key: 'createTime', ellipsisTooltip: "true"
  },
  {
    title: '操作',
    width: '150px',
    customSlot: 'operator',
    key: 'operator',
    fixed: 'right'
  }
])
const change = (page: any) => {
  //category: any,id: any
  loading.value = true
  setTimeout(() => {
    /*
    如果点击的是学院，就是查询整个学院下面的学生
    如果点击的是班级，就是查询整个班级下面的学生
    * */
    getTablePage();
    loading.value = false
  }, 1000)
}
const sortChange = (key: any, sort: number) => {
  layer.msg(`字段${key} - 排序${sort}, 你可以利用 sort-change 实现服务端排序`)
}
//列表对象
const dataSource = ref()

//列表里的启用禁用
const changeStatus = (isChecked: boolean, row: any) => {
  let paramData = {
    id:row.id,
    status:isChecked,
  }
  userUpdate(paramData).then(res=>{
    if (res.code == 0){
      layer.msg(res.msg);
      getTablePage();
    }
    // setTimeout(() => {
    //   getTablePage
    // }, 2000)

  })

}
const remove = () => {
  layer.msg(selectedKeys.value, {area: '50%'})
}
const loadDataSource = () => {
  getTablePage();
}
const model11 = ref({
  name: '',
  role: '',
  sex: '',
  status: '',
  account: ''
})
const layFormRef11 = ref()
const visible11 = ref(false)
const title = ref('新增')
const changeVisible11 = (text: any, row: any) => {
  title.value = text
  if (row != null) {
    let info = JSON.parse(JSON.stringify(row))
    model11.value = info
  } else {
    model11.value = {
      name: '',
      role: '',
      sex: '',
      status: '',
      account: ''
    }
  }
  visible11.value = !visible11.value
}
const submit11 = function () {
  layFormRef11.value.validate((isValidate: any, model: any, errors: any) => {
    layer.open({
      type: 1,
      title: '表单提交结果',
      content: `<div style="padding: 10px"><p>是否通过 : ${isValidate}</p> <p>表单数据 : ${JSON.stringify(
          model
      )} </p> <p>错误信息 : ${JSON.stringify(errors)}</p></div>`,
      shade: false,
      isHtmlFragment: true,
      btn: [
        {
          text: '确认',
          callback(index: any) {
            layer.close(index)
          }
        }
      ],
      area: '500px'
    })
  })
}
// 清除校验
const clearValidate11 = function () {
  layFormRef11.value.clearValidate()
}
// 重置表单
const reset11 = function () {
  layFormRef11.value.reset()
}

function toRemove() {
  if (selectedKeys.value.length == 0) {
    layer.msg('您未选择数据，请先选择要删除的数据', {icon: 3, time: 2000})
    return
  }
  layer.confirm('您将删除所有选中的数据？', {
    title: '提示',
    btn: [
      {
        text: '确定',
        callback: (id: any) => {
          layer.msg('您已成功删除')
          layer.close(id)
        }
      },
      {
        text: '取消',
        callback: (id: any) => {
          layer.msg('您已取消操作')
          layer.close(id)
        }
      }
    ]
  })
}

function toSubmit() {
  layer.msg('保存成功！', {icon: 1, time: 1000})
  visible11.value = false
  visible22.value = false
}

function toSubmitTree() {
  //添加
  treeInsert(model22.value).then(res => {
    if (res.code == 0) {
      layer.msg('保存成功！', {icon: 1, time: 1000})
      fetchDataTree();
    } else {
      layer.msg(res.msg, {icon: 2, time: 1000})
    }
  })


  visible11.value = false
  visible22.value = false

}

function toCancel() {
  visible11.value = false
  visible22.value = false
}

function confirm() {
  layer.msg('您已成功删除')
}

function cancel() {
  layer.msg('您已取消操作')
}


//左侧添加
const model22 = ref({
  id:'',
  name: '',
  category: '',
  parentId: ''
})


const layFormRef22 = ref()
const visible22 = ref(false)
const title22 = ref('新建')


</script>

<style scoped>
.organization-box {
  width: calc(100vw - 240px);
  height: calc(100vh - 110px);
  margin-top: 10px;
  box-sizing: border-box;
  background-color: #fff;
  overflow: hidden;
}

.left-tree {
  display: inline-block;
  padding: 20px 15px 0 5px;
  height: 1200px;
  border-right: 1px solid #e6e6e6;
  box-sizing: border-box;
  position: relative;
}

/* todo layui-tree-entry 设置无效 */
.layui-tree-entry {
  position: relative;
  padding: 10px 0;
  height: 20px;
  line-height: 20px;
  white-space: nowrap;
}

.isFold {
  position: absolute;
  top: 36%;
  right: -10px;
  width: 26px;
  height: 26px;
  line-height: 26px;
  border-radius: 13px;
  background-color: #fff;
  border: 1px solid #e6e6e6;
  cursor: pointer;
}

.search-input {
  display: inline-block;
  width: 98%;
  margin-right: 10px;
}

.isChecked {
  display: inline-block;
  background-color: #e8f1ff;
  color: red;
}
</style>